package com.zb.factory.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zb.entity.ZjFactoryAccountBalance;
import com.zb.entity.ZjWorkOrder;
import com.zb.factory.service.ConFactoryAccountBalanceService;
import com.zb.service.ZjFactoryAccountBalanceService;
import com.zb.service.ZjWorkOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Objects;

/**
 * @Author WEN
 * @Date 2024/4/17 0017
 **/
@Service
public class ConFactoryAccountBalanceServiceImpl implements ConFactoryAccountBalanceService {
    @Resource
    private ZjFactoryAccountBalanceService factoryAccountBalanceService;
    @Resource
    private ZjWorkOrderService workOrderService;

    // 扣除冻结/占用金额
    @Override
    public void deductionFreezeByFactoryId(Long factoryId, BigDecimal price) {
        factoryAccountBalanceService.updateFreezePriceById(factoryId, price);
    }

    // 扣除冻结/占用金额
    @Override
    public void deductionFreezeByWorkIds(boolean deductionMoney, List<Long> workIds) {
        if (CollectionUtil.isEmpty(workIds)) {
            return;
        }
        List<ZjWorkOrder> orderList = workOrderService.getFactoryAllFeeByIds(workIds);
        if (CollectionUtil.isEmpty(orderList)) {
            return;
        }
        List<Long> factoryIds = orderList.stream().filter(f -> null != f.getFactoryId() && f.getFactoryId() != 0).map(ZjWorkOrder::getFactoryId).distinct().toList();
        if (CollectionUtil.isEmpty(factoryIds)) {
            return;
        }
        QueryWrapper<ZjFactoryAccountBalance> wrapper = new QueryWrapper<>();
        wrapper.select("id", "money", "freeze_money")
                        .in("id", factoryIds);
        List<ZjFactoryAccountBalance> accountBalanceList = factoryAccountBalanceService.list(wrapper);
        BigDecimal price = null;
        for (ZjFactoryAccountBalance balance : accountBalanceList) {
            price = orderList.stream().filter(f -> Objects.equals(f.getFactoryId(), balance.getId())).map(ZjWorkOrder::getModulePrice).reduce(new BigDecimal("0.0"), BigDecimal::add);
            balance.setFreezeMoney(balance.getFreezeMoney().subtract(price));
            if (deductionMoney) balance.setMoney(balance.getMoney().subtract(price));
        }
        factoryAccountBalanceService.updateBatchById(accountBalanceList);
    }
}
